﻿namespace SharePoint.ImportExport.StsadmExtension
{
    using System;
    using System.Text;

    using Microsoft.SharePoint.StsAdmin;
    using SharePoint.ImportExport.Core;

    public class ImporterExtension : ISPStsadmCommand 
    {
        private static string logS;

        string ISPStsadmCommand.GetHelpMessage(string command)
        {
            StringBuilder helpMsg = new StringBuilder();
            helpMsg.Append("Import content to SharePoint:\r\n");
            helpMsg.Append("\tstsadm.exe\r\n\t-o importData\r\n");
            helpMsg.Append("\t\t-root Web Application root site\r\n");
            helpMsg.Append("\t\t-folder Folder containing the struct.xml file\r\n");
            helpMsg.Append("\r\nOptional:\r\n");
            helpMsg.Append("\t\t-ManagedPath Managed path (Sites etc)\r\n");
            helpMsg.Append("\t\t-SiteName Site name of new site\r\n");
            helpMsg.Append("-ImportToExistingSite true|false\r\n");
            helpMsg.Append("-ImportToExistingLibrary true|false\r\n");
            helpMsg.Append("-ImportSecurity true|false\r\n");
            helpMsg.Append("-DateFormat {dateformat} ie \"dd.MM.YYYY\"\r\n");

            helpMsg.Append("-ReportLevel Information|Warning|Error\r\n");

            helpMsg.Append("\r\n\t\tExample : stsadm -o importData -root http://localhost -folder c:\\export -ImportToExistingSite true -ImportToExistingLibrary false -ImportSecurity true -DateFormat dd.MM.YYYY \r\n");
            return helpMsg.ToString();
        }

        int ISPStsadmCommand.Run(string command, System.Collections.Specialized.StringDictionary keyValues, out string returnValue)
        {
            returnValue = string.Empty;
            string dateFormat = String.Empty;
            if (keyValues.ContainsKey("DateFormat"))
            {
                dateFormat = keyValues["DateFormat"];
                Console.WriteLine("Changing the date format to {0}", dateFormat);

                if (dateFormat != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern)
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = dateFormat;
                }
            }
            
            string siteCollectionRootURL = keyValues["root"];
            string managedPath = String.Empty;
            string siteName = String.Empty;
            string folderName = keyValues["folder"];
            bool allowImportToExistingSites = false;
            if (keyValues.ContainsKey("ImportToExistingSite"))
            {
                allowImportToExistingSites = bool.Parse(keyValues["ImportToExistingSite"]);
            }

            bool allowImportToExistingLibraries = false;
            if (keyValues.ContainsKey("ImportToExistingLibrary"))
            {
                allowImportToExistingLibraries = bool.Parse(keyValues["ImportToExistingLibrary"]);
            }

            bool importSecurity = false;
            if (keyValues.ContainsKey("ImportSecurity"))
            {
                importSecurity = bool.Parse(keyValues["ImportSecurity"]);
            }

            ErrorLevel level = ErrorLevel.Warning;
            if (keyValues.ContainsKey("ReportLevel"))
            {
                level = (ErrorLevel)Enum.Parse(typeof(ErrorLevel), keyValues["ReportLevel"]);
            }

            if (keyValues.ContainsKey("ImportToExistingSite"))
            {
                allowImportToExistingSites = bool.Parse(keyValues["ImportToExistingSite"]);
            }

            if (keyValues.ContainsKey("ManagedPath"))
            {
                managedPath = keyValues["ManagedPath"];
            }

            if (keyValues.ContainsKey("SiteName"))
            {
                siteName = keyValues["SiteName"];
            }

            if (siteCollectionRootURL != null && folderName != null)
            {
                Logger.Init("import" + DateTime.Now.ToString("MMddHHmm") + ".log", level);
                Logger.LogDataSendingEvent += new Logger.LogDataEventHandler(IncomingEventLogData);
                Importer.ImportWrapper importer = new Importer.ImportWrapper();
                string contentDeploymentFiles;
                importer.Process(folderName, siteCollectionRootURL, allowImportToExistingSites, allowImportToExistingLibraries, importSecurity, true, managedPath, siteName, out contentDeploymentFiles);
                importer.ImportData(contentDeploymentFiles, folderName, siteCollectionRootURL, true);
                returnValue = "Done";
            }
            else
            {
                // If missing args, display an error message
                if (siteCollectionRootURL == null)
                {
                    returnValue += "Missing required argument : root\r\n";
                }

                if (folderName == null)
                {
                    returnValue += "Missing required argument : folder\r\n";
                }

                //// Add also the default help message
                returnValue += "\r\n" + ((ISPStsadmCommand)this).GetHelpMessage(null);
            }

            return 0;
        }

        private static void IncomingEventLogData(object sender, SPEventArgs e)
        {
            string msg = e.Message;
            int pos = msg.IndexOf("-");
            if (pos > 0)
            {
                msg = msg.Substring(pos + 1);
            }

            string logArgs = DateTime.Now.ToLongTimeString() + ":  " + msg;
            logS += logArgs;
            Console.WriteLine(logArgs);
        }
    }
}
